import lombok.SneakyThrows;
import org.assertj.core.util.Maps;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 测试restTemplate拦截器
 *
 * @author Zijian Liao
 * @since 1.0.0
 */
public class RestTemplateDemo {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new RestTemplateInterceptor());
        restTemplate.setInterceptors(interceptors);
        System.out.println(restTemplate.getForObject("http://my-goods/goods/get", String.class));
    }

    static class RestTemplateInterceptor implements ClientHttpRequestInterceptor {

        @SneakyThrows
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            return execution.execute(new MyRequestWrapper(request), body);
        }
    }

    static class MyRequestWrapper extends HttpRequestWrapper {
        /**
         * 模拟注册中心存储服务信息
         */
        private final Map<String, String> serverMap = Maps.newHashMap("my-goods", "127.0.0.1:8081");


        public MyRequestWrapper(HttpRequest request) {
            super(request);
        }

        @SneakyThrows
        @Override
        public URI getURI() {
            URI uri = super.getRequest().getURI();
            String server = uri.getHost();
            // 模拟从注册中心取出真实ip
            String host = serverMap.get(server);
            // 替换URI
            return new URI(uri.getScheme() + "://" + host + uri.getRawPath());
        }
    }
}
